﻿Imports System.ComponentModel
Imports System.IO
Imports System.Diagnostics
Imports System.Data.OleDb
Imports SpeechLib
Imports System.Threading

Public Class 主页

    Public root As Integer = 0
    Public l_h As Integer = 6
    Public l_m As Integer = 35
    Public port As String
    Public id As String = ""
    Public i As Integer = 1
    Public pname As String
    Private Delegate Sub dele_1()
    Dim Driver As Thread
    Private Delegate Sub VoidShow(ByRef i As String, ByRef b As Boolean)
    Public t As Boolean = False

    Public Sub ts(ByVal a As String)
        If t = True Then
            Dim b As String = TextBox5.Text + vbCrLf
            b = b + a
            TextBox5.Text = b
        End If
    End Sub

    Public Sub Neww()
        If Dir(".\data", vbDirectory) = "" Then
            MkDir(".\data")
            SetAttr(".\data", vbHidden)
        End If
        Try
            Dim XDoc As New Xml.XmlDocument
            XDoc.Load(".\data\init.xml")
            Dim XReader As New Xml.XmlNodeReader(XDoc)
            Dim ParaName As String = ""
            While XReader.Read
                Select Case XReader.NodeType
                    Case Xml.XmlNodeType.Element
                        ParaName = XReader.Name
                    Case Xml.XmlNodeType.Text
                        Select Case ParaName
                            Case "port" : port = XReader.Value
                            Case "l_hour" : l_h = XReader.Value
                            Case "l_min" : l_m = XReader.Value
                            Case "pname" : pname = XReader.Value
                        End Select
                End Select
            End While

        Catch ex As Exception
            System.IO.File.Create(".\data\init.xml").Dispose()
            ts(ex.ToString)
        End Try
        Try
            Me.QdTableAdapter.Fill(Me.QdDataSet.qd)
        Catch ex As Exception
            ts(ex.ToString)
        End Try
        If port = "" Then
            MsgBox("首次使用请先配置")
            修改.Visible = True
        Else
            If SerialPort1.IsOpen Then
                SerialPort1.Close()
            End If
            With SerialPort1
                .PortName = Replace(port, vbLf, "")
                .BaudRate = 57600

                .Parity = IO.Ports.Parity.None '奇偶校验
                .DataBits = 8 '数据位
                .StopBits = IO.Ports.StopBits.One '停止位
            End With
            '打开
            Try
                SerialPort1.Open()
            Catch ex As Exception
                ts(ex.ToString)
            End Try
        End If
        ts("刷新完成")
    End Sub



    Private Function Accsu(ByVal b As String, ByVal l As String, ByVal n As String， ByVal cl As String) As String
        Dim z As String
        '定义一个OLEDB连接并实例化它
        Dim con As New OleDbConnection
        '定义一个OLEDB命令并实例化他
        Dim cmd As New OleDbCommand
        '定义一个OLEDBReader方法来读取数据库
        Dim dr As OleDbDataReader
        '初始化con的连接属性，使用OLEDB模式
        con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=.\data\qd.accdb"
        '打开OLEDB数据连接
        con.Open()
        '初始化OLEDB命令的连接属性为con,这个需要你理解下
        cmd.Connection = con
        '初始化OLEDB命令的语句 就是查询 什么字段从什么表 条件是ID等于你在t1中输入的内容
        cmd.CommandText = "select " & l & " from " & b & " where " & cl & "=" & n
        '执行OLEDB命令以ExecuteReader()方式，并返回一个OLEDBReader，赋值给dr
        dr = cmd.ExecuteReader()
        '判断下dr中是否有数据。如果有就把第一个值赋值给t2的值
        If dr.Read() Then
            z = dr(0)
            Accsu = z
        Else
            Accsu = ""
        End If
        dr.Close()
        con.Close()
        '函数Accsu说明：b为查询的表，l为输出的列，n为查询列的值,cl为查询的列
    End Function
    Public Sub Up(ByVal a As String)
        Dim odConnection As New OleDbConnection With {
            .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=.\date\qd.accdb"
        }
        odConnection.Open()
        Dim str As New System.Text.StringBuilder
        str.Append(a)
        Dim cmdn As New OleDb.OleDbCommand(str.ToString, odConnection)
        cmdn.ExecuteNonQuery()
        odConnection.Close()
    End Sub


    Function DateGet() As String
        DateGet = Format(DateTime.Now, "yyyy/MM/dd")
    End Function

    Function TimeGet() As String
        TimeGet = Format(DateTime.Now, "yyyy-MM-dd HH:mm:ss")
    End Function

    Function Late() As Boolean

        If Val(Format(DateTime.Now, "HH")) = l_h And Val(Format(DateTime.Now, "mm")) <= l_m Then
            Late = False
        Else
            Late = True
        End If
    End Function

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckForIllegalCrossThreadCalls = False
        Try
            Me.QdTableAdapter.Fill(Me.QdDataSet.qd)
        Catch ex As Exception
            ts(ex.ToString)
            Try
                System.Diagnostics.Process.Start(".\TouchClassManage(86).exe")
            Catch ex2 As Exception
                MsgBox("X86版缺失，请重新安装")
                ts(ex2.ToString)
            End Try
            Me.Close()
        End Try
        Neww()
        Try
            Dim fp As StreamReader
            fp = File.OpenText(".\data\通知.txt")
            Text = fp.ReadToEnd
            Me.TextBox3.Text = Replace(Text, Chr(10) + Chr(13), "")
            fp.Close()
        Catch ex As Exception
            File.Create(".\data\通知.txt").Dispose()
            ts(ex.ToString)
        End Try
    End Sub



    '发送数据
    Public Function SendHEX(ByVal dat() As Byte) As String
        Try
            SerialPort1.DiscardOutBuffer()
            SerialPort1.Write(dat, 0, dat.Length)
            ts("发数据")
            SendHEX = "0"
        Catch ex As Exception
            SendHEX = ("发送错误，代码：" + ex.ToString)
            ts(ex.ToString)
        End Try
    End Function



    '接收数据
    Public Function GetHEX() As Byte()
        Dim byteToRead As Int16 = SerialPort1.BytesToRead()
        ts("等待接收")
        Do While byteToRead < 8
            byteToRead = SerialPort1.BytesToRead()
        Loop
        ts("收到")
        Dim ch(byteToRead) As Byte
        SerialPort1.Read(ch, 0, byteToRead)
        GetHEX = ch
    End Function

    Public Sub Dj(ByRef a As String, ByRef b As Boolean)
        If a <> 0 Then
            If b = False Then
                Me.Label15.Text = Me.Label15.Text + a + "被管理员签到"
            End If
            Me.TextBox2.Text = a
            Dim name As String = ""
            name = Accsu("main", "nam", Me.TextBox2.Text, "fid")
            If name <> Nothing Then
                Me.Label13.Text = （Val(Me.Label13.Text) + 1).ToString
                Me.Label6.Text = name
                Me.TextBox1.Text = Me.TextBox1.Text + (name + "，签到于" + TimeGet() + "，备注：" + Me.TextBox4.Text) + vbCrLf
                Try
                    PictureBox1.Load(".\data\picture\" + pname + Me.TextBox2.Text + name + ".JPG")
                Catch ex As Exception
                    ts(ex.ToString)
                End Try
                Me.Label8.Text = Accsu("main", "time", Me.TextBox2.Text, "fid")
                Me.Label10.Text = Accsu("main", "late_time", Me.TextBox2.Text, "fid")
                If Late() Then
                    Dim l As Integer = Val(Label10.Text) + 1
                    Up("UPDATE main SET main.late_time = " & l & " WHERE ((fid=" + Me.TextBox2.Text + "));")
                    Up("INSERT INTO qd ( nam,fid, [time], late, other ) VALUES ('" + name + "'," + Me.TextBox2.Text + ",#" + TimeGet() + "#," + "1,'" + Me.TextBox4.Text + "')")
                    '迟到数据库
                    Me.Label12.Text = Me.Label12.Text + name + " "
                    Dim MyVoice As New SpeechLib.SpVoice
                    Dim tmpStr As String
                    tmpStr = name + "，迟到" + l.ToString + "次，现已签到：" + Me.Label13.Text + "人"
                    Try
                        MyVoice.Speak(tmpStr, SpeechVoiceSpeakFlags.SVSFlagsAsync)
                    Catch ex As Exception
                        ts(ex.ToString)
                    End Try
                    Me.PictureBox2.Visible = False
                    Me.PictureBox3.Visible = True
                    Me.Label10.Text = l
                Else
                    Dim d As Integer = Val(Label8.Text) + 1
                    Up("UPDATE main SET main.time = " & d & " WHERE ((fid=" + Me.TextBox2.Text + "));")
                    Up("INSERT INTO qd ( nam,fid, [time], late, other ) VALUES ('" + name + "'," + Me.TextBox2.Text + ",#" + TimeGet() + "#," + "0,'" + Me.TextBox4.Text + "')")
                    '正常数据库
                    Dim MyVoice As New SpeechLib.SpVoice
                    Dim tmpStr As String
                    tmpStr = name + "，谢谢"
                    Try
                        MyVoice.Speak(tmpStr, SpeechVoiceSpeakFlags.SVSFlagsAsync)
                    Catch ex As Exception
                        ts(ex.ToString)
                    End Try
                    Me.PictureBox2.Visible = True
                    Me.PictureBox3.Visible = False
                    Me.Label8.Text = d
                End If
                Me.TextBox2.Text = ""
                Me.TextBox4.Text = ""
            Else
                MsgBox("无信息，请联系管理员")
            End If
        End If
        Try
            Me.QdTableAdapter.Fill(Me.QdDataSet.qd)
        Catch ex As Exception
            ts(ex.ToString)
        End Try
        Me.TextBox2.Text = ""
        Dim i As Integer = 0
        指纹识别.Text = "处理中"
        Neww()
        指纹识别.Text = "请扫描"
    End Sub

    Public Sub GetID(Optional a As Boolean = False)
        If SerialPort1.IsOpen Then
            i = 0
        Else
            MsgBox("硬件未在指定端口连接,请检查连接后重试")
            Button2.PerformClick()
        End If
        While i = 0
            ts("循环检测")
            Try
                Dim getimage(12) As Byte
                getimage(0) = &HEF
                getimage(1) = &H1
                getimage(2) = &HFF
                getimage(3) = &HFF
                getimage(4) = &HFF
                getimage(5) = &HFF
                getimage(6) = &H1
                getimage(7) = &H0
                getimage(8) = &H3
                getimage(9) = &H1
                getimage(10) = &H0
                getimage(11) = &H5
                Dim zt As String = SendHEX(getimage)
                If zt = "0" Then
                    Dim js() As Byte
                    js = GetHEX()
                    Do While js(9) <> &H0
                        ts("等接收")
                        SendHEX(getimage)
                        js = GetHEX()
                    Loop
                    If zt = "0" Then
                        Dim sc(13) As Byte
                        sc(0) = &HEF
                        sc(1) = &H1
                        sc(2) = &HFF
                        sc(3) = &HFF
                        sc(4) = &HFF
                        sc(5) = &HFF
                        sc(6) = &H1
                        sc(7) = &H0
                        sc(8) = &H4
                        sc(9) = &H2
                        sc(10) = &H1
                        sc(11) = &H0
                        sc(12) = &H8
                        zt = SendHEX(sc)
                        js = GetHEX()
                        ts("收到，等转码")
                        If js(9) = &H0 And zt = "0" Then
                            Dim bd(17) As Byte
                            bd(0) = &HEF
                            bd(1) = &H1
                            bd(2) = &HFF
                            bd(3) = &HFF
                            bd(4) = &HFF
                            bd(5) = &HFF
                            bd(6) = &H1
                            bd(7) = &H0
                            bd(8) = &H8
                            bd(9) = &H4
                            bd(10) = &H1
                            bd(11) = &H0
                            bd(12) = &H0
                            bd(13) = &H0
                            bd(14) = &HC8
                            bd(15) = &H0
                            bd(16) = &HD6
                            zt = SendHEX(bd)
                            js = GetHEX()
                            ts("成功，等识别")
                            If js(9) = &H0 And zt = "0" Then
                                If a = False Then
                                    ts("识别到，处理")
                                    Me.Invoke(New VoidShow(AddressOf Dj), js(11).ToString, True) '用New构造委托，再用Invoke执行  
                                    ts("完成")
                                    i = 0
                                Else
                                    id = js(11)
                                    i = 1
                                End If
                                i = 0
                            Else
                                ts("不识别")
                            End If
                        Else
                            ts("不清晰")
                            i = 0
                        End If
                    Else
                        ts("无指纹")
                        i = 0
                    End If
                Else
                    i = 0
                End If
            Catch ex As Exception
                i = 0
                ts(ex.ToString)
            End Try
        End While
        ts("循环检测停")
        Try
            Driver.Abort() '终止线程  
        Catch ex As Exception
            ts(ex.ToString)
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        i = 1
        Me.Button1.Visible = True
        Me.Button2.Visible = False
        指纹识别.Visible = False
        Try
            Driver.Abort()
        Catch
        End Try
    End Sub

    Private Sub ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem.Click
        Dim p As String = InputBox("输入管理密码")
        If p = "Aaclass123" Then
            修改.Visible = True
        Else
            MsgBox("必须为管理员")
        End If
    End Sub

    Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
        System.Diagnostics.Process.Start("https://gitee.com/LBDLMOS/C008_TouchManage")
    End Sub


    Private Sub 随机抽取ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 随机抽取ToolStripMenuItem.Click
        Dim myRND As New Random
        Dim a As String = myRND.Next(1, 51)
        Dim MyVoice As New SpeechLib.SpVoice
        Dim tmpStr As String
        tmpStr = Accsu("main", "nam", a, "fid")
        Try
            MyVoice.Speak(tmpStr, SpeechVoiceSpeakFlags.SVSFlagsAsync)
        Catch ex As Exception
            ts(ex.ToString)
        End Try
    End Sub

    Private Sub 刷新ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 刷新ToolStripMenuItem.Click
        Neww()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            Me.Button2.Visible = True
            Me.Button1.Visible = False
            指纹识别.Visible = True
            Driver = New Thread(AddressOf GetID)
            Driver.Name = "读取指纹"
            Driver.Start()
        Catch ex As Exception
            MsgBox("操作太频繁,代码：" + ex.ToString)
            ts(ex.ToString)
        End Try
    End Sub

    Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
        root += 1
        If root = 5 Then
            root = 0
            Me.TextBox5.Visible = Not Me.TextBox5.Visible
            Me.Label15.Text = Me.Label15.Text + "你已进入开发者模式"
            t = True
        End If
    End Sub

    Private Sub TextBox5_Click(sender As Object, e As EventArgs) Handles TextBox5.Click
        TextBox5.Text = ""
    End Sub
End Class
